#pragma once
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"

namespace HttpServerModule
{
    using http_hander_t = std::function<void(Request& req,Response& res)>;
    using namespace TcpserverModule;
    class HttpServer
    {
    public:
        HttpServer(int port)
            : _tsvr(std::make_shared<TcpServer>(port))
        {
            _tsvr->RegisterHandler([this](SockPtr ret, InetAddr client)
                                   { return this->Handler(ret, client); });
        }
        void Start()
        {
            _tsvr->Loop();
        }
        void RegisterHander(std::string path,http_hander_t server)
        {
            _route[path] = server;
        }
        bool CheckSafe(std::string& path)
        {
            auto it = _route.find(path);
            return it != _route.end();
        }
        void Handler(SockPtr ret, InetAddr client)
        {
            LOG(LogLevel::INFO) << "new client fd: " << ret->FD() << "client info: " << client.Addr();
            // 接受数据
            std::string http_str;
            ret->TcpRecv(&http_str);

            std::cout << "--------------------------------" << std::endl;
            std::cout << http_str << std::endl;
            std::cout << "--------------------------------" << std::endl;
            
            Request req;
            Response res;
            //1. 静态请求 
            req.Deserialize(http_str);
            if (req.HasArgs())
            {
                //2. 请求带参数，如何处理参数呢?       
                std::string path = req.Path();              
                if (CheckSafe(path))
                    _route[path](req,res); //执行方法
                else 
                    res.Build(req);
            }
            else 
            {
                res.Build(req);
            }
            //认为到现在过来的是一个完整的报文，不进行读取不完善处理
            std::string returnstr;
            res.Serialize(&returnstr);
  
            ret->TcpSend(returnstr);
        }
       
        ~HttpServer() {}

    private:
        std::shared_ptr<TcpServer> _tsvr;
        std::unordered_map<std::string,http_hander_t> _route;
    };
}